<template>
<div class="app-container calendar-list-container">
  <div class="filter-container">
    <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="平台名称" v-model="listQuery.name"> </el-input>
    <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
    <el-button class="filter-item"  v-if="platformManager_btn_add"  style="margin-left: 10px;" @click="handleCreate" type="primary" icon="edit">添加</el-button>
  </div>
  <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">
    <el-table-column align="center" label="序号" width="65"> <template scope="scope">
          <span>{{scope.row.id}}</span>
        </template> </el-table-column>
    <el-table-column width="110" align="center" label="平台名称"> <template scope="scope">
        <span>{{scope.row.platformName}}</span>
      </template> </el-table-column>
    <el-table-column width="110" align="center" label="平台登录名称"> <template scope="scope">
        <span>{{scope.row.platformLoginName}}</span>
      </template> </el-table-column>
    <el-table-column width="160" align="center" label="平台Id"> <template scope="scope">
            <span>{{scope.row.platformId}}</span>
          </template> </el-table-column>
    <el-table-column width="450" align="center" label="平台简介"> <template scope="scope">
            <span>{{scope.row.platformIntroduction}}</span>
          </template> </el-table-column>
    <el-table-column width="160" align="center" label="创建时间"> <template scope="scope">
          <span>{{scope.row.createTime}}</span>
        </template> </el-table-column>
    <el-table-column width="160" align="center" label="更新时间"> <template scope="scope">
          <span>{{scope.row.updateTime}}</span>
        </template> </el-table-column>
    <el-table-column width="110" align="center" label="最后更新人"> <template scope="scope">
            <span>{{scope.row.operatorName}}</span>
          </template> </el-table-column>
    <el-table-column align="center" label="操作" width="355"> <template scope="scope">
        <el-button v-if="platformManager_btn_edit" size="small" type="success" @click="handleUpdate(scope.row)">编辑
        </el-button>
        <el-button v-if="platformManager_btn_del" size="small" type="danger" @click="handleDelete(scope.row)">删除
        </el-button>
        <el-button size="small" type="info" @click="handleDetail(scope.row)">详情
        </el-button>
        <el-button size="small" type="danger" @click="completeInfo(scope.row)">信息完善
        </el-button>
      </template> </el-table-column>
  </el-table>
  <div v-show="!listLoading" class="pagination-container">
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
  </div>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
    <el-form :model="form" :rules="rules" ref="form" label-width="120px">
      <el-form-item label="平台名称" prop="platformName">
        <el-input v-model="form.platformName" placeholder="请输入平台名称"></el-input>
      </el-form-item>
      <el-form-item label="平台登录名称" prop="platformLoginName">
        <el-input v-model="form.platformLoginName" placeholder="请输入平台登录名称"></el-input>
      </el-form-item>
      <el-form-item label="平台logo" prop="platformLogoStr">
        <div class="imgSrc" @click="uploadLogo">
          <img v-if="base64Img" :src="base64Img" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </div>
        <input type="file" name="file" id="upload_platformSVG" @change="changeImg($event)" accept="image/svg+xml" style="display: none">
      </el-form-item>
      <el-form-item v-if="dialogStatus == 'create'" label="手机号" >
        <el-input v-model="form.mobilePhone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="平台简介">
        <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 5}" placeholder="请输入内容" v-model="form.platformIntroduction"> </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel('form')">取 消</el-button>
      <el-button v-if="dialogStatus == 'create'" type="primary" @click="create('form')">确 定</el-button>
      <el-button v-else type="primary" @click="update('form')">确 定</el-button>
    </div>
  </el-dialog>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogCompleteInfoVisible">
    <el-form :model="extentForm"  ref="extentForm" label-width="100px">
      <el-form-item label="企业名称" prop="companyName">
        <el-input v-model="extentForm.companyName" placeholder="请填写企业名称"></el-input>
      </el-form-item>
      <el-form-item label="经营范围" prop="businessScope">
        <el-input v-model="extentForm.businessScope" placeholder="请填写经营范围"></el-input>
      </el-form-item>
      <el-form-item label="注册工商号" prop="businessNo">
        <el-input v-model="extentForm.businessNo" placeholder="请填写注册工商号"></el-input>
      </el-form-item>
      <el-form-item label="法人姓名" prop="legalPersonName">
        <el-input v-model="extentForm.legalPersonName" placeholder="请填写法人姓名"></el-input>
      </el-form-item>
       <el-form-item label="法人证件类型" prop="legalPersonCredType">
        <el-select v-model="extentForm.legalPersonCredType" placeholder="请选择">
          <el-option
            v-for="item in credTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
       </el-select>
      </el-form-item>
       <el-form-item label="法人证件号码" prop="legalPersonCredNo">
        <el-input v-model="extentForm.legalPersonCredNo" placeholder="请填写法人证件号码"></el-input>
      </el-form-item>
      <el-form-item label="营业执照" prop="businessLicence">
        <el-upload
          class="upload-demo"
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :file-list="fileList2"
          :before-upload="beforeUpload"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="extentForm.phone" placeholder="请填写联系电话"></el-input>
      </el-form-item>
      <el-form-item label="企业座机" prop="mobile">
        <el-input v-model="extentForm.mobile" placeholder="请填写企业座机"></el-input>
      </el-form-item>
      <el-form-item label="企业传真" prop="fax">
        <el-input v-model="extentForm.fax" placeholder="请填写企业传真"></el-input>
      </el-form-item>
      <el-form-item label="企业网址" prop="fax">
        <el-input v-model="extentForm.httpAddress" placeholder="请填写企业网址"></el-input>
      </el-form-item>
      <el-form-item label="注册资金" prop="registeredCapital">
        <el-input v-model="extentForm.registeredCapital" placeholder="请填写注册资金"></el-input>
      </el-form-item>
      <el-form-item label="企业地址" prop="registeredCapital">
        <el-input v-model="extentForm.companyAddress" placeholder="企业地址"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancelExtendForm('extentForm')">取 消</el-button>
      <el-button v-if="dialogStatus == 'info'" type="primary" @click="createExtendInfo('extentForm')">确 定</el-button>
      <el-button v-else type="primary" @click="updateExtendInfo('extentForm')">确 定</el-button>
    </div>
  </el-dialog>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogChannelConfigVisible">
    <el-form :model="channelConfigForm"  ref="channelConfigForm" label-width="100px">

    </el-form>
  </el-dialog>
</div>
</template>

<script>
import { page, getObj, delObj, putPlatObj, addPlatObj, addPlatformExtend, upload, getPlatformExtend, updatePlatformExtend } from '@/api/crm/platform/index'
import { mapGetters } from 'vuex'
export default {
  name: 'user',
  data() {
    return {
      form: {
        platformId: undefined,
        platformName: undefined,
        platformLoginName: undefined,
        platformIntroduction: undefined,
        token: undefined,
        operatorName: undefined,
        operatorId: undefined,
        platformLogoStr: undefined,
        mobilePhone: undefined
      },
      base64Img: '',
      fileList2:
        [],
      extentForm: {
        platformId: undefined,
        companyName: undefined,
        businessScope: undefined,
        businessNo: undefined,
        legalPersonName: undefined,
        legalPersonCredType: undefined,
        legalPersonCredNo: undefined,
        businessLicence: undefined,
        phone: undefined,
        mobile: undefined,
        fax: undefined,
        httpAddress: undefined,
        registeredCapital: undefined,
        companyAddress: undefined,
        token: undefined
      },
      channelConfigList: [],
      channelConfigForm: {

      },
      credTypeOptions: [
        {
          value: '0',
          label: '身份证'
        }, {
          value: '1',
          label: '户口本'
        }, {
          value: '2',
          label: '护照'
        }, {
          value: '3',
          label: '军官证'
        }, {
          value: '4',
          label: '士兵证'
        }, {
          value: '5',
          label: '港澳居民往来内地通行证'
        }, {
          value: '6',
          label: '台湾通报往来内地通行证'
        }, {
          value: '7',
          label: '临时身份证'
        }, {
          value: '8',
          label: '外国人居留证'
        }, {
          value: '9',
          label: '警官证'
        }, {
          value: 'x',
          label: '其他证件'
        }
      ],
      rules: {
        platformName: [
          {
            required: true,
            message: '请输入平台名称',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        platformLoginName: [
          {
            required: true,
            message: '请输入平台登录名称',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        platformLogoStr: [
          {
            required: true,
            message: '请上传平台图片',
            trigger: 'blur'
          }
        ],
        platformIntroduction: [
          {
            required: true,
            message: '请输入平台简介',
            trigger: 'blur'
          },
          {
            min: 5,
            max: 20,
            message: '长度在 5 到 20 个字符',
            trigger: 'blur'
          }
        ]
      },
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined
      },
      sexOptions: ['男', '女'],
      dialogFormVisible: false,
      dialogCompleteInfoVisible: false,
      dialogChannelConfigVisible: false,
      dialogStatus: '',
      userManager_btn_edit: false,
      userManager_btn_del: false,
      userManager_btn_add: false,
      textMap: {
        update: '编辑',
        create: '创建',
        info: '信息完善',
        channelConfig: '支付通道'
      },
      tableKey: 0
    }
  },
  created() {
    this.getList()
    this.platformManager_btn_edit = this.elements['platformManager:btn_edit']
    this.platformManager_btn_del = this.elements['platformManager:btn_del']
    this.platformManager_btn_add = this.elements['platformManager:btn_add']
  },
  computed: {
    ...mapGetters([
      'elements',
      'token',
      'name',
      'userId'
    ])
  },
  watch: {
    base64Img() {
      this.form.platformLogoStr = this.base64Img
    }
  },
  methods: {
    uploadLogo: function() {
      const input = document.getElementById('upload_platformSVG')
      input.click()
    },
    changeImg: function(e) {
      console.log('====changeImg===================================')
      console.log(e)
      var _this = this
      var imgLimit = 1024
      var files = e.target.files
      console.log('====files===================================')
      console.log(files)
      var image = new Image()
      if (files.length > 0) {
        var dd = 0
        // var timer = setInterval(function(){
        if (files.item(dd).type !== 'image/svg+xml') {
          return false
        }

        if (files.item(dd).size > imgLimit * 102400) {
          // to do sth
          console.log('====文件过大===================================')
        } else {
          console.log('====文件大小小于最大值===================================')
          image.src = window.URL.createObjectURL(files.item(dd))
          image.onload = function() {
            // 默认按比例压缩
            var w = image.width
            var h = image.height
            var scale = w / h
            w = 200
            h = w / scale
            // 默认图片质量为0.7，quality值越小，所绘制出的图像越模糊
            var quality = 0.7
            // 生成canvas
            var canvas = document.createElement('canvas')
            var ctx = canvas.getContext('2d')
            // 创建属性节点
            var anw = document.createAttribute('width')
            anw.nodeValue = w
            var anh = document.createAttribute('height')
            anh.nodeValue = h
            canvas.setAttributeNode(anw)
            canvas.setAttributeNode(anh)
            ctx.drawImage(image, 0, 0, w, h)
            // var ext = image.src.substring(image.src.lastIndexOf(".")+1).toLowerCase();//图片格式
            // var base64 = canvas.toDataURL("image/"+ext, quality );
            var base64 = canvas.toDataURL('image/svg+xml', quality)
            _this.base64Img = base64

            console.log('====_this.base64Img ===================================')
            console.log(_this.base64Img)
            // 回调函数返回base64的值
            // if(_this.imgArr.length<=4){
            //     _this.imgArr.unshift('');
            //     _this.imgArr.splice(0, 1, base64);//替换数组数据的方法，此处不能使用：this.imgArr[index] = url;
            //   if(_this.imgArr.length>=5){
            //       _this.allowAddImg = false;
            //   }
            // }
          }
        }
        // if(dd<files.length-1){
        //   dd++;
        // }else{
        //   clearInterval(timer);
        // }
        // },1000)
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    beforeUpload(file) {
      console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
      console.log(file)
      const fd = new FormData()
      fd.append('file', file)
      upload(fd)
        .then(response => {
          console.log('==============================================')
          console.log(response)
          this.extentForm.businessLicence = response.name
        })
      return false
    },
    getList() {
      this.listLoading = true
      page(this.listQuery)
        .then(response => {
          this.list = response.data.rows
          this.total = response.data.total
          this.listLoading = false
        })
    },
    handleFilter() {
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleChannelConfig() {
      this.dialogStatus = 'channelConfig'
      this.dialogChannelConfigVisible = true
    },
    handleUpdate(row) {
      getObj(row.id)
        .then(response => {
          this.form = response.data
          this.dialogFormVisible = true
          this.dialogStatus = 'update'
        })
    },
    completeInfo(row) {
      this.resetExtentForm()
      this.dialogStatus = 'info'
      this.dialogCompleteInfoVisible = true
      this.extentForm.platformId = row.platformId
      getPlatformExtend(row.platformId)
        .then(response => {
          console.log('---------------------')
          console.log(response)
          if (response.extend !== undefined) {
            this.extentForm = response.extend
          }
          if (response.channelConfig !== undefined) {
            this.channelConfigList = response.channelConfig
          }
        })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delObj(row.id)
            .then(() => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            })
        })
    },
    create(formName) {
      console.log('=====formName==========================================')
      console.log(formName)
      const set = this.$refs
      this.form.token = this.token
      this.form.platformLevel = '02'
      set[formName].validate(valid => {
        if (valid) {
          addPlatObj(this.form)
            .then(response => {
              console.log(response)
              if (response.code === '0000') {
                this.dialogFormVisible = false
                this.getList()
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '失败',
                  message: response.message,
                  type: 'failed',
                  duration: 2000
                })
              }
            })
        } else {
          return false
        }
      })
    },
    createExtendInfo(formName) {
      console.log('------this.extentForm.id--------')
      console.log(this.extentForm.id)
      if (this.extentForm.id === null || this.extentForm.id === '') {
        this.extentForm.token = this.token
        addPlatformExtend(this.extentForm)
          .then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '补充成功',
              type: 'success',
              duration: 2000
            })
            this.dialogCompleteInfoVisible = false
          })
      } else {
        updatePlatformExtend(this.extentForm)
          .then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '补充成功',
              type: 'success',
              duration: 2000
            })
            this.dialogCompleteInfoVisible = false
          })
      }
    },
    updateExtendInfo(formName) {

    },
    cancel(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    cancelExtendForm(formName) {
      this.dialogCompleteInfoVisible = false
      this.resetExtentForm()
    },
    update(formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false
          this.form.password = undefined
          this.form.operatorName = this.name
          this.form.operatorId = this.userId
          putPlatObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    resetTemp() {
      this.form = {
        username: undefined,
        name: undefined,
        sex: '男',
        password: undefined,
        description: undefined
      }
    },
    handleDetail(row) {
      this.$router.push({ path: '/organizationManager/platformDetail', query: { row: row }})
    },
    resetExtentForm() {
      this.extentForm = {
        platformId: undefined,
        companyName: undefined,
        businessScope: undefined,
        businessNo: undefined,
        legalPersonName: undefined,
        legalPersonCredType: undefined,
        legalPersonCredNo: undefined,
        businessLicence: undefined,
        phone: undefined,
        mobile: undefined,
        fax: undefined,
        httpAddress: undefined,
        registeredCapital: undefined,
        companyAddress: undefined
      }
    }
  }
}
</script>
<style>
.el-dialog {
  width: 1200px !important;
}
</style>